﻿using HtmlAgilityPack;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace fund
{
    public static class HtmlParseUtitly
    {
        /// <summary>
        /// 通过网页URL获取HtmlNode
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static HtmlNode GetHtmlNodeByUrl(string url, Encoding encoding)
        {
            string htmlSource = GetHtmlSource(url, encoding);
            if (string.IsNullOrEmpty(htmlSource)) return null;
            return GetHtmlNodeByHtml(htmlSource);
        }

        /// <summary>
        /// 通过网页html源代码获取HtmlNode
        /// </summary>
        /// <param name="htmlSource"></param>
        /// <returns></returns>
        public static HtmlNode GetHtmlNodeByHtml(string htmlSource)
        {
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(htmlSource);
            HtmlNode rootNode = document.DocumentNode;
            return rootNode;
        }

        /// <summary>
        /// 获取网页源代码
        /// </summary>
        public static string GetHtmlSource(string url, Encoding encoding)
        {
            WebRequest request;
            string result = "";
            try
            {
                request = WebRequest.Create(url);

                using (WebResponse response = request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                    result = reader.ReadToEnd();
            }
            catch
            {
                result = "";
            }
            return result;
        }

        /// <summary>
        /// 获取单节点的值
        /// </summary>
        /// <param name="srcNode"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetNodeInnerText(HtmlNode srcNode, string path)
        {
            HtmlNode temp = srcNode.SelectSingleNode(path);
            if (temp != null)
                return temp.InnerText;
            return "";
        }

        public static List<string> GetNodesInnerText(HtmlNode srcNode, string path)
        {
            List<string> nodeValues = new List<string>();
            HtmlNodeCollection spanNodeList = srcNode.SelectNodes(path);

            foreach (HtmlNode categoryNode in spanNodeList)
            {
                if (categoryNode != null)
                    nodeValues.Add(categoryNode.InnerText);
            }
            return nodeValues;
        }
    }
}